package com.ranqianhui.ojbackenduserservice.controller.internal;

import com.ranqianhui.ojbackendcommon.common.ErrorCode;
import com.ranqianhui.ojbackendcommon.constant.UserConstant;
import com.ranqianhui.ojbackendcommon.exception.BusinessException;
import com.ranqianhui.ojbackendcommon.utils.JwtTool;
import com.ranqianhui.ojbackendmodel.model.entity.User;
import com.ranqianhui.ojbackenduserservice.service.UserService;
import com.ranqianhuii.ojbackendserviceclient.service.UserClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

@RestController
@RequestMapping("/inner")
public class UserControllerinternal implements UserClient {
    @Resource
    private UserService userService;
    @Resource
    private JwtTool jwtTool;
    @GetMapping("/get/id")
    public User getById(long userId) {
        User user = userService.getById(userId);
        return user;
    }

    @GetMapping("/get/ids")
    public List<User> listByIds(Collection<Long> idList) {
        List<User> users = userService.listByIds(idList);

        return users;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        String token = (String)request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        Long userId = jwtTool.parseToken(token);
        if (userId == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        User user = this.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return user;
    }

    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        String token =(String)request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        Long userId = jwtTool.parseToken(token);
        User user = this.getById(userId);
        return isAdmin(user);
    }

}
